package com.khh.base.common.config;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.khh.base.assertion.AssertArgument;
import com.khh.base.assertion.AssertValue;
import com.khh.base.util.IoUtil;

public class BaseCommonConfigUnit {

	private static final Logger logger = Logger
			.getLogger(BaseCommonConfigUnit.class);

	public final static String CONFIG_FILE_NAME = "base.common.properties";

	private static Map<String, BaseCommonConfigUnit> instances = new HashMap<String, BaseCommonConfigUnit>();

	Properties properties = new Properties();

	private BaseCommonConfigUnit() {

	}

	public static BaseCommonConfigUnit getInstance() {
		return BaseCommonConfigUnit.getInstance(null);
	}

	public static BaseCommonConfigUnit getInstance(String resource) {
		BaseCommonConfigUnit instance = null;

		synchronized (instances) {
			if (resource == null) {
				logger.debug("use default base common config resource file "
						+ CONFIG_FILE_NAME + ".");
				resource = CONFIG_FILE_NAME;
			}

			instance = (BaseCommonConfigUnit) instances.get(resource);

			if (instance == null) {
				logger.debug("creating  BaseCommonConfigUnit.");
				instance = new BaseCommonConfigUnit();

				// 解析配置文件
				try {
					instance.iniConfigDocument(resource);
				} catch (IOException e) {
					logger.error("载入配置文件出现IO错误." + e.getMessage(), e);
					return null;
				}

				instances.put(resource, instance);
			}

		}
		return instance;
	}

	public String getProperty(String property) {

		AssertArgument.isNotNullAndNotEmpty(property, "property");

		logger.debug("读取配置文件属性" + property);

		// logger.debug("在配置文件中没有找到属性：" + property);
		String value = this.properties.getProperty(property);
		logger.debug("读取配置文件属性:" + property + ",值：" + value);

		return value;
	}

	public String getProperty(String property, String defaultValue) {
		String value = this.getProperty(property);

		if (AssertValue.isNotNullAndNotEmpty(value)) {
			return value;
		} else {
			return defaultValue;
		}

	}

	private void iniConfigDocument(String resource) throws IOException {
		properties.load(new ByteArrayInputStream(IoUtil
				.readBytesForClassPath(resource)));
	}

}
